package com.yanqu.road.server.manger.monopolymarket;

import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.monopolymarket.*;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketBackEndConfig;
import com.yanqu.road.entity.monopolymarket.config.MonopolyMarketResConfigData;
import com.yanqu.road.entity.monopolymarket.group.MonopolyMarketServerGroup;
import com.yanqu.road.entity.monopolymarket.office.log.MonopolyMarketOfficeUserSeatLogData;
import com.yanqu.road.entity.monopolymarket.office.log.MonopolyMarketUserPhysicalChangeLogData;
import com.yanqu.road.entity.monopolymarket.resgrab.*;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.monopolymarket.MonopolyMarketBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.UnionHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.monopolymarket.MonopolyMarketProto;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.monopolymarket.MonopolyMarketModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.BitUtil;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.util.ConcurrentHashSet;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 榷场
 * @Author cwq
 * @Data 2021/8/11 17:06
 */
public class MonopolyMarketMgr extends TempMgr {

    public static Logger logger = LogManager.getLogger(MonopolyMarketMgr.class.getName());

    /**
     * 服务器启动需要找跨服拿到对应的分组信息
     */
    public static MonopolyMarketServerGroup group;

    /**
     *  配置 k:id
     */
    public static Map<Integer, MonopolyMarketResConfigData> resConfigMap = new HashMap<>();

    /**
     * 榷署资源配置
     */
    public static List<MonopolyMarketResConfigData> officeResConfigList = new ArrayList<>();

    /**
     * 榷署资源配置 k:level
     */
    public static Map<Integer,MonopolyMarketResConfigData> officeResConfigMap = new HashMap<>();


    /*********************资源争夺战配置*************************/

    /**
     * 资源争夺战资源配置 k:type
     */
    public static Map<Integer, List<MonopolyMarketResConfigData>> resGrabResConfigMap = new HashMap<>(2);

    /**
     * 配置  k：资源类型  k:level
     */
    public static Map<Integer, Map<Integer,MonopolyMarketResConfigData>> resConfigLevelMap = new HashMap<>(2);

    /**
     * 当前分组资源争夺战地图信息
     */
    public static Map<Integer, MonopolyMarketResGrabMap> resGrabMapMap = new HashMap<>();

    /**
     * 生成格子的 拓展参数配置
     */
    public static MonopolyMarketBackEndConfig backEndConfig;


    /*********************边关要塞配置*************************/

    /**
     * 要塞配置 k:id
     */
    public static Map<Integer,MonopolyMarketResConfigData> fortressResConfigMap = new HashMap<>();


    /**
     * 开服是否同步分组配置
     */
    public static boolean isSyn = false;

    //需要上传基本信息的玩家
    private static Set<Long> needUploadUserInfoSet = new ConcurrentHashSet<>();

    // 需要上传玩家派遣对象 k:userId k:系统id v 对象集合
    private static ConcurrentHashMap<Long,ConcurrentHashMap<Integer,Set<Integer>>> needUploadObjectInfoMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        if(!reload()){
            return false;
        }

        SystemCrossServerGroupMgr.getAccessMap().put(eSystemId.MonopolyMarket.getValue(), new ICrossServerGroupAccess() {
            @Override
            public int getGroupIdByServerId(long serverId) {
                if(group != null){
                    return (int)(group.getGroupId());
                }
                return (int)serverId;
            }
            @Override
            public Set<Long> getGroupServer(int groupId) {
                if(group != null){
                    return new HashSet<>(group.getServerList());
                }
                return null;
            }

            @Override
            public void reloadServerGroup() {
                return;
            }
        });
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        List tempOfficeResConfigList = new ArrayList<>();
        Map<Integer, List<MonopolyMarketResConfigData>> tempResGrabResConfigMap = new HashMap<>(2);
        Map<Integer, Map<Integer,MonopolyMarketResConfigData>> tempResConfigLevelMap = new HashMap<>(2);
        Map<Integer, MonopolyMarketResConfigData> tempResConfigMap = new HashMap<>();
        Map<Integer,MonopolyMarketResConfigData> tempOfficeResConfigMap = new HashMap<>();
        Map<Integer,MonopolyMarketResConfigData> tempFortressResConfigMap = new HashMap<>();

        int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
        MonopolyMarketBackEndConfig monopolyMarketBackEndConfig = MonopolyMarketBussiness.getMonopolyMarketBackEndConfig(channelId);
        List<MonopolyMarketResConfigData> configList = MonopolyMarketBussiness.getMonopolyMarketResConfigDataList();
        // 检查后台配置
        if(!MonopolyMarketCommonMgr.checkBackEndResConfig(monopolyMarketBackEndConfig,configList)){
            return false;
        }
        backEndConfig = monopolyMarketBackEndConfig;

        for (MonopolyMarketResConfigData item : configList){
            tempResConfigMap.put(item.getId(),item);

            if(item.getType() == eMonopolyMarketResType.OFFICE.getValue()){
                tempOfficeResConfigList.add(item);
                tempOfficeResConfigMap.put(item.getLevel(),item);
            }else if(item.getType() == eMonopolyMarketResType.RES_KING.getValue() ||
                    item.getType() == eMonopolyMarketResType.RES_QUEEN.getValue() ){
                List<MonopolyMarketResConfigData> list = tempResGrabResConfigMap.get(item.getType());
                if(list == null){
                    list = new ArrayList<>();
                    tempResGrabResConfigMap.put(item.getType(),list);
                }
                list.add(item);
                Map<Integer,MonopolyMarketResConfigData> map = tempResConfigLevelMap.get(item.getType());
                if (map == null) {
                    map = new HashMap<>();
                    tempResConfigLevelMap.put(item.getType(),map);
                }
                map.put(item.getLevel(),item);
            }else if(item.getType() == eMonopolyMarketResType.FORTRESS.getValue()){
                tempFortressResConfigMap.put(item.getId(),item);
            }
        }

        officeResConfigList = tempOfficeResConfigList;
        resGrabResConfigMap = tempResGrabResConfigMap;
        resConfigLevelMap = tempResConfigLevelMap;
        resConfigMap = tempResConfigMap;
        officeResConfigMap = tempOfficeResConfigMap;
        fortressResConfigMap = tempFortressResConfigMap;

        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        group = MonopolyMarketBussiness.getMonopolyMarketServerGroup(GameServer.getInstance().getServerId());
        if(group != null){
            initMap();
        }
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        if(group != null){
            if (group.isInsertOption()) {
                MonopolyMarketBussiness.addMonopolyMarketServerGroup(group);
            } else if (group.isUpdateOption()) {
                MonopolyMarketBussiness.updateMonopolyMarketServerGroup(group);
            }
        }
        return true;
    }

    /**
     * 判断系统是否开放
     * @return
     */
    public static boolean isSystemOpenTime(){
        // 没有分组
        if(MonopolyMarketMgr.group == null){
            return false;
        }
        return MonopolyMarketMgr.group.getState() == 1;
    }

    /**
     * 玩家是否能进入系统
     * @param player
     * @return
     */
    public static boolean canEnterSystem(GamePlayer player){
        if (!SystemOpenMgr.systemOpen(player, eSystemId.MonopolyMarket.getValue())) {
            // 系统未解锁
            return false;
        }
        return isSystemOpenTime();
    }


    /**
     * 玩家离线
     */
    public static void offLine(GamePlayer player){
        if(MonopolyMarketMgr.canEnterSystem(player)){
            MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
            if(marketModule.inSystemId < 0){
                return;
            }
            marketModule.inSystemId = -1;
            MonopolyMarketProto.MonopolyMarketExitReqMsg.Builder builder = MonopolyMarketProto.MonopolyMarketExitReqMsg.newBuilder();
            builder.setIsOffOnline(true);
            exit(player,builder);
        }
    }

    public static void exit(GamePlayer player,MonopolyMarketProto.MonopolyMarketExitReqMsg.Builder builder){
        player.sendPacket(CrossProtocol.C_CROSS_MONOPOLY_MARKET_EXIT, builder);
    }

    /**
     * 刷新玩家体力 抢夺次数
     * @param player
     * @param forceUpdate
     */
    public static void refreshUser(GamePlayer player ,boolean forceUpdate,boolean isSyn){
        // 刷新抢夺次数
        MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
        int now = DateHelper.getCurrentSecond();
        synchronized (marketModule){
            if(!resetUser(marketModule)){
                refreshOfficeTeaReward(marketModule,now);
                refreshPhysical(marketModule,now,forceUpdate);
                refreshRobTimes(marketModule,now);
                refreshResGrabDispatch(marketModule,now);
            }
        }
        if(isSyn){
            marketModule.synRoleData();
        }
    }

    /**
     * 刷新玩家每日抢夺次数
     * @param marketModule
     * @param time
     */
    public static void refreshRobTimes(MonopolyMarketModule marketModule,int time){
        if(DateHelper.getDiffDayNum(marketModule.baseData.getDailyOfficeRefreshTime()) != 0 ){
            // 每日刷新
            marketModule.baseData.setOfficeRobTimes(0);
            marketModule.baseData.setDailyOfficeRefreshTime(time);
        }
    }

    /**
     * 重置玩家信息
     * 1 榷署结束后发送茶的邮件  移除榷署位置
     * 2 隔周重置榷署体力
     */
    public static boolean resetUser(MonopolyMarketModule marketModule){
        int now = DateHelper.getCurrentSecond();
        int endTime = MonopolyMarketCommonMgr.getResetOfficeTime((int)(marketModule.baseData.getPhysicalRefreshTime()), ConfigMgr.getOfficeEndSecond());
        long oldPhysicalRefreshTime = marketModule.baseData.getPhysicalRefreshTime();
        boolean isReset = false;
        synchronized(marketModule){
            if(marketModule.baseData.getPhysicalRefreshTime() <= endTime && endTime <= now ) {
                // 重置玩家
                refreshOfficeTeaReward(marketModule,endTime);
                refreshPhysical(marketModule,endTime,true);
                sendOfficeRewardMail(marketModule);
                resetOfficeSeat(marketModule);
                marketModule.baseData.setPhysicalRefreshTime(now);
                marketModule.baseData.setOfficeRobTimes(0);
                marketModule.baseData.setDailyOfficeRefreshTime(now);
                isReset = true;
            }
            int weekEndTime = DateHelper.getWeekBeginTimestamp(now);
            if(oldPhysicalRefreshTime < weekEndTime){
                LogMgr.addMonopolyMarketOfficeUserSeatLogData(new MonopolyMarketOfficeUserSeatLogData(marketModule.getUserId(),marketModule.baseData.getOfficeCurPos(),marketModule.baseData.getOfficeLevel(),marketModule.baseData.getOfficeNo(),0,marketModule.baseData.getPhysical(),marketModule.baseData.getOfficeSeatTime(),now));

                int oldValue = marketModule.baseData.getPhysical();
                marketModule.baseData.setPhysical(GameConfig.MONOPOLYMARKET_INITIAL_GUANYIN_MAX);
                marketModule.baseData.setPhysicalRefreshTime(now);
                // 每周清空要塞派遣的玩家数据
                marketModule.getFortressDispatchMap().clear();
                LogMgr.addMonopolyMarketUserPhysicalChangeLogData(new MonopolyMarketUserPhysicalChangeLogData(marketModule.getUserId(), marketModule.baseData.getOfficeCurPos(), marketModule.baseData.getOfficeLevel(), marketModule.baseData.getOfficeNo(), 0, oldValue, marketModule.baseData.getPhysical(), DateHelper.getCurrentSecond()));
            }
        }
        return isReset;
    }

    /**
     * @param marketModule
     */
    private static void refreshResGrabDispatch(MonopolyMarketModule marketModule,int time){
        if(DateHelper.getDiffDayNum(marketModule.baseData.getDailyResGrabRefreshTime()) != 0){
            marketModule.getCurDispatchInfoListMap().clear();
            marketModule.baseData.setDailyResGrabRefreshTime(time);
        }
    }

    /**
     * 增加体力
     * @param marketModule
     * @param addValues
     */
    public static void addPhysical(GamePlayer player,MonopolyMarketModule marketModule ,int addValues){
        refreshUser(player,true,false);
        marketModule.baseData.setPhysical(marketModule.baseData.getPhysical() + addValues);
    }

    /**
     * 计算入座需要消耗多少元宝
     * @return
     */
    public static int calSitDownConsumeGold(GamePlayer player){
        MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
        if(marketModule.baseData.getOfficeRobTimes() < GameConfig.MONOPOLYMARKET_FREESEIZE_1){
            return 0;
        }
        int diffTimes = marketModule.baseData.getOfficeRobTimes() - GameConfig.MONOPOLYMARKET_FREESEIZE_1;
        return Math.min(diffTimes * ConfigMgr.getOfficeConsume().addConsume + ConfigMgr.getOfficeConsume().initConsume, ConfigMgr.getOfficeConsume().maxConsume);
    }

    /**
     * 计算玩家体力上限
     * @return
     */
    public static int calPhysicalMaxLimit(MonopolyMarketModule marketModule){
        if(marketModule.baseData.getOfficeLevel() > 0){
            MonopolyMarketResConfigData configData = officeResConfigMap.get(marketModule.baseData.getOfficeLevel());
            if(configData != null){
                return configData.getLimit();
            }
        }
        return GameConfig.MONOPOLYMARKET_INITIAL_GUANYIN_MAX;
    }

    /**
     * 计算玩家的产出速度
     * @return
     */
    public static int calOfficeSeatProductionRate(MonopolyMarketModule marketModule){
        if(marketModule.baseData.getOfficeCurPos() >= 0 && MonopolyMarketMgr.group != null){
            MonopolyMarketResConfigData configData = officeResConfigMap.get(marketModule.baseData.getOfficeLevel());
            return MonopolyMarketCommonMgr.calResRate(MonopolyMarketMgr.group.getServerList().size(),configData.rewardValue1,configData.rewardAdd1,configData.getId(),MonopolyMarketMgr.backEndConfig,marketModule.baseData.getOfficeNo());
        }
        return GameConfig.MONOPOLYMARKET_INITIAL_GUANYIN_SPEED;
    }

    /**
     * 重置玩家数据
     */
    public static void resetUserData(int bit ,boolean isSyn){
        int now = DateHelper.getCurrentSecond();
        List<GamePlayer> playerLis = GamePlayerMgr.getAllOnlinePlayer();
        for (GamePlayer player : playerLis){
            // 结算
            if (!SystemOpenMgr.systemOpen(player, eSystemId.MonopolyMarket.getValue())) {
                continue;
            }
            MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
            for(eMonopolyMarketResType resType : eMonopolyMarketResType.values()){
                if(BitUtil.get(bit, resType.getValue() - 1)) {
                    // 重置榷场系统
                    if (resType == eMonopolyMarketResType.OFFICE) {
                        MonopolyMarketMgr.refreshPhysical(marketModule, now,false);
                        MonopolyMarketMgr.refreshOfficeTeaReward(marketModule, now);
                        LogMgr.addMonopolyMarketOfficeUserSeatLogData(new MonopolyMarketOfficeUserSeatLogData(marketModule.getUserId(),marketModule.baseData.getOfficeCurPos(),marketModule.baseData.getOfficeLevel(),marketModule.baseData.getOfficeNo(),0,marketModule.baseData.getPhysical(),marketModule.baseData.getOfficeSeatTime(),now));

                        MonopolyMarketMgr.resetOfficeSeat(marketModule);
                        marketModule.baseData.setOfficeRobTimes(0);
                        marketModule.baseData.setDailyOfficeRefreshTime(now);
                        marketModule.clearOfficeReport();
                    } else if (resType == eMonopolyMarketResType.RES_KING || resType == eMonopolyMarketResType.RES_QUEEN) {
                        // 重置派遣的大臣
                        // 重置派遣的美女
                        marketModule.getCurDispatchInfoListMap(resType.getValue(),true).clear();
                        synchronized (marketModule.resGrabReportList){
                            marketModule.resGrabReportList.clear();
                        }
                    } else if(resType == eMonopolyMarketResType.FORTRESS){
                        marketModule.getFortressDispatchMap().clear();
                    }
                }
            }
            if(isSyn){
                player.getModule(MonopolyMarketModule.class).synRoleData();
            }
        }
        logger.info("game 榷署重置玩家数据，bit:{}，玩家数量：{}",bit,playerLis.size());
    }

    public static MonopolyMarketProto.MonopolyMarketOfficeReportEntity.Builder builderMonopolyMarketOfficeReportEntity(MonopolyMarketReportData reportData){
        MonopolyMarketProto.MonopolyMarketOfficeReportEntity.Builder builder = MonopolyMarketProto.MonopolyMarketOfficeReportEntity.newBuilder();
        builder.setType(reportData.getType());
        builder.setRobId(reportData.getRobId());
        builder.setRobInfo(PlayerBasePb.parsePlayerBaseTempMsg(reportData.getRobInfo()));
        builder.setPosIndex(reportData.getPosIndex());
        builder.setIsWin(reportData.getIsWin());
        builder.setTime(reportData.getTime());
        return builder;
    }

    public static MonopolyMarketProto.MonopolyMarketUserEntity.Builder builderMonopolyMarketUserEntity(MonopolyMarketModule marketModule){
        MonopolyMarketProto.MonopolyMarketUserEntity.Builder builder = MonopolyMarketProto.MonopolyMarketUserEntity.newBuilder();
        builder.setUserId(marketModule.baseData.getUserId());
        builder.setPhysical(marketModule.baseData.getPhysical());
        builder.setRefreshTime(marketModule.baseData.getPhysicalRefreshTime());
        builder.setOfficeLevel(marketModule.baseData.getOfficeLevel());
        builder.setOfficeSeatTime(marketModule.baseData.getOfficeSeatTime());
        builder.setOfficeCurPosIndex(marketModule.baseData.getOfficeCurPos());
        builder.setOfficeRobTimes(marketModule.baseData.getOfficeRobTimes());
        builder.setUserId(marketModule.baseData.getUserId());
        builder.setDailyRefreshTime(marketModule.baseData.getDailyOfficeRefreshTime());
        builder.setHasTip(marketModule.baseData.getHasTip());
        builder.setTeaLastNum(marketModule.baseData.getTeaLastNum());
        builder.setTeaLastGetTime(marketModule.baseData.getTeaLastGetTime());
        if(marketModule.officeReportList.size() > 0){
            builder.setHasNewOfficeReport(marketModule.baseData.getEnterOfficeReportLastTime() < marketModule.officeReportList.get(marketModule.officeReportList.size() - 1).getTime());
        }
        if(marketModule.resGrabReportList.size() > 0){
            builder.setHasNewResGrabReport(marketModule.baseData.getEnterResGrabReportLastTime() < marketModule.resGrabReportList.get(marketModule.resGrabReportList.size() - 1).getTime());
        }
        return builder;
    }

    public static MonopolyMarketProto.MonopolyMarketResConfigEntity.Builder builderMonopolyMarketResConfigEntity(MonopolyMarketResConfigData item){
        MonopolyMarketProto.MonopolyMarketResConfigEntity.Builder builder = MonopolyMarketProto.MonopolyMarketResConfigEntity.newBuilder();
        builder.setId(item.getId());
        builder.setLevel(item.getLevel());
        builder.setType(item.getType());
        builder.setReward(item.getReward());
        builder.setRewardAdd(item.getRewardAdd());
        builder.setLimit(item.getLimit());
        builder.setCost(item.getCost());
        builder.setMonster(item.getMonster());
        builder.setSeize(item.getSeize());
        builder.setPic(item.getPic());
        builder.setReturncost(item.getReturncost());
        builder.setNpcReturncost(item.getNpcReturncost());
        builder.setNpcList(item.getNpcList());
        return builder;
    }

    public static MonopolyMarketProto.MonopolyMarketResGrabDispatchTimesEntity.Builder builderMonopolyMarketResGrabDispatchTimesEntity(MonopolyMarketResGrabDispatchInfo item){
        MonopolyMarketProto.MonopolyMarketResGrabDispatchTimesEntity.Builder builder = MonopolyMarketProto.MonopolyMarketResGrabDispatchTimesEntity.newBuilder();
        builder.setId(item.getDispatchId());
        builder.setPosIndex(item.getPosIndex());
        builder.setSeatTime(item.getSeatTime());
        return builder;
    }

    /**
     *
     * @param player
     * @param patrons 要计算的当前门客
     * @param list 队伍门客
     * @return
     */
    public static MonopolyMarketProto.MonopolyMarketPatronsEntity.Builder builderMonopolyMarketPatronsEntity(GamePlayer player,UserPatrons patrons,List<UserPatrons> list){
        int addPlus = 0;
        // 计算该门客的自己战斗加成
        addPlus = getAddPlus(patrons);
        PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(patrons.getPatronsId());
        // 计算同类型门客
        for(UserPatrons member : list){
            if(member.getPatronsId() == patrons.getPatronsId()){
                continue;
            }
            PatronsInfo memberPatronsInfo = PatronsMgr.getPatronsInfo(member.getPatronsId());
            if(patronsInfo.getOccupation() == memberPatronsInfo.getOccupation()){
                addPlus += getAddPlus(member);
            }
        }
        // 算葫芦娃加成
        addPlus += PatronsMgr.getMonopolyMarketPatronsPlus(player,eSkillType.CALABASH_BROTHERS_KING.getValue());

        MonopolyMarketProto.MonopolyMarketPatronsEntity.Builder builder = MonopolyMarketProto.MonopolyMarketPatronsEntity.newBuilder();
        builder.setPatronsId(patrons.getPatronsId());
        builder.setLevel(patrons.getLevel());
        builder.setStageLv(patrons.getStageLv());
        builder.setSkinId(patrons.getSkinId());
        long earn = patrons.getAbility().longValue();
        builder.setEarn(earn);
        builder.setAddPlus(addPlus);
        builder.setPromotionId(patrons.getShowPromotionId());
        return builder;
    }

    public static int getAddPlus(UserPatrons patrons){
        int addPlus = 0;
        if(patrons != null){
            for (UserPatronsSkill userPatronsSkill : patrons.getSkillList()){
                SkillInfo skillInfo = SkillMgr.getSkillInfo(userPatronsSkill.getSkillId());
                if(skillInfo == null){
                    continue;
                }
                if (skillInfo.getType() == eSkillType.BattleEffect.getValue() ) {
                    addPlus += SkillMgr.getSkillAddition(skillInfo, userPatronsSkill.getSkillLv());
                }
            }
        }
        return addPlus;
    }

    public static MonopolyMarketProto.MonopolyMarketBeautyEntity.Builder builderMonopolyMarketBeautyEntity(UserBeauty beauty,int addPlus){
        MonopolyMarketProto.MonopolyMarketBeautyEntity.Builder builder = MonopolyMarketProto.MonopolyMarketBeautyEntity.newBuilder();
        builder.setAddPlus(addPlus);
        builder.setId(beauty.getBeautyId());
        builder.setSkinId(beauty.getSkinId());
        builder.setValue(beauty.getTotalGlamour());
        return builder;
    }

    public static MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity builderMonopolyMarketFortressPatronsDispatchEntity(UserPatrons patrons){
        MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity.Builder builder = MonopolyMarketProto.MonopolyMarketFortressPatronsDispatchEntity.newBuilder();
        builder.setPatronsId(patrons.getPatronsId());
        builder.setValue(patrons.getAbility().longValue());
        builder.setPlus(getAddPlus(patrons));
        builder.setSkinId(patrons.getSkinId());
        builder.setPromotionId(patrons.getShowPromotionId());
        return builder.build();
    }

    /**
     * 重置榷署位置
     * @param marketModule
     */
    public static void resetOfficeSeat(MonopolyMarketModule marketModule){
        marketModule.baseData.setOfficeCurPos(-1);
        marketModule.baseData.setOfficeSeatTime(0);
        marketModule.baseData.setOfficeLevel(0);
        marketModule.baseData.setOfficeNo(0);
        marketModule.baseData.setTeaLastGetTime(DateHelper.getCurrentSecond());
    }

    /**
     * 榷署入座
     * @param marketModule
     * @param seatInfo
     * @param level
     * @param no
     */
    public static void sitOffice(MonopolyMarketModule marketModule, MonopolyMarketProto.MonopolyMarketOfficeEntity seatInfo,int level,int no){
        marketModule.baseData.setOfficeCurPos(seatInfo.getPosIndex());
        marketModule.baseData.setOfficeSeatTime((int)(seatInfo.getSeatTime()));
        marketModule.baseData.setOfficeLevel(level);
        marketModule.baseData.setOfficeNo(no);
        marketModule.baseData.setTeaLastGetTime((int)(seatInfo.getSeatTime()));
    }

    /**
     * 加榷署战报
     * @param player 有可能为空
     * @param msg
     */
    public static void addReport(GamePlayer player,MonopolyMarketProto.MonopolyMarketSynAttackToGameServerMsg msg){
        UserBaseInfo attackInfo = null;
        if(!msg.hasAttackInfo()) {
            attackInfo = UserMgr.getUserBaseInfo(msg.getAttackId(), GameServer.getInstance().getServerId());
        }else {
            attackInfo = PlayerBasePb.parseToUserBaseInfo(msg.getAttackInfo());
        }
        MonopolyMarketReportData report = new MonopolyMarketReportData();
        report.setType(msg.getType());
        report.setUserId(msg.getRobedId());
        report.setIsWin(msg.getIsWin());
        report.setPosIndex(msg.getPosIndex());
        report.setRobId(msg.getAttackId());
        report.setRobInfo(attackInfo);
        report.setTime(DateHelper.getCurrentSecond());
        report.setInsertOption();
        MonopolyMarketModule marketModule = null;
        if(player != null){
            marketModule = player.getModule(MonopolyMarketModule.class);
            if(msg.getType() == eMonopolyMarketResType.OFFICE.getValue()){
                synchronized (marketModule.officeReportList){
                    while (marketModule.officeReportList.size() >= GameConfig.MONOPOLYMARKET_KEEPINFO_1){
                        marketModule.officeReportList.remove(0);
                    }
                    marketModule.officeReportList.add(report);
                }
                // 去跨服结算
                if(msg.getIsWin()){
                    marketModule.baseData.setHasTip(true);
                    player.sendPacket(YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_MONOPOLY_MARKET_GET_USER_DATA));
                }
            }else {
                synchronized (marketModule.resGrabReportList){
                    while (marketModule.resGrabReportList.size() >= GameConfig.MONOPOLYMARKET_KEEPINFO_2){
                        marketModule.resGrabReportList.remove(0);
                    }
                    marketModule.resGrabReportList.add(report);
                }
                if(msg.getIsWin()){
                    marketModule.baseData.setHasTip(true);
                    MonopolyMarketMgr.leaveResGrabPoint(player,msg.getType(),msg.getPosIndex(),false);
                    if(marketModule.inSystemId >= 0){
                        // 去跨服领取奖励
                        player.sendPacket(YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_MONOPOLY_MARKET_RES_GRAB_RECEIVE_REWARD));
                    }
                }
            }
        }else {
            // 直接入库
            MonopolyMarketBussiness.addMonopolyMarketReportData(report);
        }
        if(msg.getIsWin()){
            String mailTitle = null;
            String mailContent = null;
            String language = UserMgr.getLanguage(msg.getRobedId());
            String serverName = ServerListMgr.getServerName(attackInfo.getServerId(),language);
            if(msg.getType() == eMonopolyMarketResType.OFFICE.getValue()){
                MonopolyMarketResConfigData configData = MonopolyMarketMgr.officeResConfigMap.get(msg.getLevel());
                String MONOPOLYMARKET_NAME = "MONOPOLYMARKET_NAME_" + configData.getMonster();
                // 加邮件通知 强夺者区服|强夺者名字|level|no
                mailTitle = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_OFFICE_ROBBED_TITLE, language);
                mailContent = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_OFFICE_ROBBED_CONTENT, language);
                String posName = MultipleLanguageMgr.getContent(MONOPOLYMARKET_NAME, language);
                mailContent = StringUtils.format(mailContent, serverName,attackInfo.getNickName(),posName,msg.getNo());

            }else {
                // 加邮件通知 强夺者区服|强夺者名字|type|level|x|y
                mailTitle = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_RES_GRAB_ROBBED_TITLE, language);
                mailContent = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_RES_GRAB_ROBBED_CONTENT, language);
                String MONOPOLYMARKET_RESOURCE_NAME = "MONOPOLYMARKET_RESOURCE_NAME_" + msg.getType();
                MONOPOLYMARKET_RESOURCE_NAME = MultipleLanguageMgr.getContent(MONOPOLYMARKET_RESOURCE_NAME, language);
                mailContent = StringUtils.format(mailContent, serverName,attackInfo.getNickName(),MONOPOLYMARKET_RESOURCE_NAME,msg.getLevel(),msg.getX(),msg.getY());
            }
            MailManager.sendMail(msg.getRobedId(), eMailType.SYSTEM.getValue(), "",mailContent,mailTitle);
        }
    }

    /**
     * 校验今日是否可以再派遣
     * @param type
     * @param todayTimes
     * @return
     */
    public static int checkTodayDispatchTimes(int type, int todayTimes){
        if(type == eMonopolyMarketResType.OFFICE.getValue()){
            if(todayTimes - GameConfig.MONOPOLYMARKET_FREESEIZE_1 >= GameConfig.MONOPOLYMARKET_SEIZE_MAX_1){
                return GameErrorCode.E_MONOPOLY_MARKET_DISPATCH_LIMIT_HAS_BEEN_REACHED;
            }
        }
        return 0;
    }


    /**************************************资源争夺战*********************************************************/

    /**
     * 检查派遣数量
     * @param type
     * @param dispatchNum
     * @return
     */
    public static int checkDispatchNum(int type,int dispatchNum){
        if(type == eMonopolyMarketResType.RES_KING.getValue() && dispatchNum > GameConfig.MONOPOLYMARKET_TEAMLIMIT_MAX_2){
            return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_NO_OBJECT;
        }
        if(type == eMonopolyMarketResType.RES_QUEEN.getValue() && dispatchNum > GameConfig.MONOPOLYMARKET_TEAMLIMIT_MAX_3){
            return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_NO_OBJECT;
        }
        return 0;
    }

    /**
     * 检查派遣队伍数量
     * @param player
     * @param type
     * @return
     */
    public static int checkTeamNum(GamePlayer player,int type){
        MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
        Map map = marketModule.getCurDispatchInfoListMap(type,false);
        if(map != null ){
            if(type == eMonopolyMarketResType.RES_KING.getValue() && map.size() >= GameConfig.MONOPOLYMARKET_ARMYLIMIT_2){
                return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_TEAM_LIMIT_HAS_BEEN_REACHED;
            }
            if(type == eMonopolyMarketResType.RES_QUEEN.getValue() && map.size() >= GameConfig.MONOPOLYMARKET_ARMYLIMIT_3){
                return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_TEAM_LIMIT_HAS_BEEN_REACHED;
            }

        }
        return 0;
    }

    /**
     * 撤回据点
     * @param player
     * @param type
     * @param posIndex
     */
    public static void leaveResGrabPoint(GamePlayer player,int type,int posIndex,boolean isSyn){
        MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
        Map<Integer, Set<MonopolyMarketResGrabDispatchInfo>> map = marketModule.getCurDispatchInfoListMap(type,true);
        map.remove(posIndex);
        if(isSyn){
            player.getModule(MonopolyMarketModule.class).synRoleData();
        }
    }

    public static MonopolyMarketProto.MonopolyMarketResGrabTipEntity.Builder builderMonopolyMarketResGrabTipEntity(MonopolyMarketProto.MonopolyMarketSynPointSettlementToGameServerMsg msg){
        MonopolyMarketProto.MonopolyMarketResGrabTipEntity.Builder tipBuilder = MonopolyMarketProto.MonopolyMarketResGrabTipEntity.newBuilder();
        tipBuilder.setType(msg.getType());
        tipBuilder.setPosIndex(msg.getPosIndex());
        tipBuilder.setSide(msg.getSide());
        tipBuilder.setLevel(msg.getLevel());
        tipBuilder.setTotalTime(msg.getRewardTime());
        tipBuilder.setRobName(msg.getRobName());
        tipBuilder.addAllObjectList(msg.getDispatchObjectIdList());
        tipBuilder.setRewardNum(msg.getRewardNum());
        tipBuilder.setBuffValues(msg.getBuffValues());
        tipBuilder.setTotalRewardNum(msg.getTotalRewardNum());
        return tipBuilder;
    }

    public static void initMap(){
        initMap(eMonopolyMarketResType.RES_KING.getValue());
        initMap(eMonopolyMarketResType.RES_QUEEN.getValue());
    }

    public static void initMap(int type){
        List<MonopolyMarketResConfigData> list = resGrabResConfigMap.get(type);
        MonopolyMarketResGrabMap map = MonopolyMarketCommonMgr.initResGrabMap(type, MonopolyMarketMgr.group ,list,MonopolyMarketMgr.backEndConfig,false);
        resGrabMapMap.put(type,map);
    }

    /**
     * 榷场更新门客信息
     * @param player
     * @param patronsList
     */
    public static void synPatronsAbility(GamePlayer player,List<UserPatrons> patronsList){
        for (UserPatrons item : patronsList){
            MonopolyMarketMgr.addNeedUploadObjectInfo(player,eMonopolyMarketResType.RES_KING.getValue(),item.getPatronsId());
            MonopolyMarketMgr.addNeedUploadObjectInfo(player,eMonopolyMarketResType.FORTRESS.getValue(),item.getPatronsId());
        }
    }

    /**
     * @param type
     * @param rewardNum
     * @return
     */
    public static Property addReward(int type, int rewardNum){
        Property property = new Property();
        int goods = MonopolyMarketCommonMgr.getGoodsId(type);
        property.addProperty(goods, BigInteger.valueOf(rewardNum));
        return property;
    }

    /**
     * 校验可鼓舞的次数
     * @param type
     * @param times
     * @return
     */
    public static int checkBuffTimes(int type, int times){
        if(type == eMonopolyMarketResType.RES_KING.getValue() && GameConfig.MONOPOLYMARKET_BUFF_TIMES_2 < times){
            return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_BUFF_CANNOT_EXCEED_THE_UPPER_LIMIT;
        }else if(type == eMonopolyMarketResType.RES_QUEEN.getValue() && GameConfig.MONOPOLYMARKET_BUFF_TIMES_3 < times){
            return GameErrorCode.E_MONOPOLY_MARKET_RES_GRAB_BUFF_CANNOT_EXCEED_THE_UPPER_LIMIT;
        }
        return 0;
    }

    /**
     * 计算鼓舞的元宝数
     * @param type
     * @param times
     * @return
     */
    public static int calBuffIngots(int type, int times){
        int totalNum = 0;
        MonopolyMarketConsume consume = ConfigMgr.getResGrabConsumeMap().get(type);
        if(consume != null){
            for (int i = 1; i <= times; i++) {
                totalNum += Math.min((times - 1) * consume.addConsume + consume.initConsume, consume.maxConsume);
            }
        }
        return totalNum;
    }

    public static void uploadUserInfo(){
        List<Long> list = new ArrayList<>();
        synchronized (needUploadUserInfoSet) {
            for (long userId : needUploadUserInfoSet){
                list.add(userId);
            }
            needUploadUserInfoSet.clear();
        }
        if(list.size() > 0){
            for (long uid : list) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(uid);
                if(player != null){
                    player.getModule(MonopolyMarketModule.class).syncPlayerBaseInfoToCross();
                }
            }
        }
    }

    public static void addNeedUploadUserInfo(GamePlayer player){
        //玩家是否有解锁
        if(!canEnterSystem(player)){
            return;
        }
        synchronized (needUploadUserInfoSet){
            needUploadUserInfoSet.add(player.getUserId());
        }
    }

    public static void addNeedUploadObjectInfo(GamePlayer player,int type ,Integer objectId){
        if(!canEnterSystem(player)){
            return;
        }
        if(!MonopolyMarketCommonMgr.isSystemOpen(MonopolyMarketMgr.group, type)){
            return;
        }
        if(type == eMonopolyMarketResType.FORTRESS.getValue() && !MonopolyMarketCommonMgr.isDispatchFortress()){
            return;
        }
        synchronized (needUploadObjectInfoMap){
            ConcurrentHashMap<Integer,Set<Integer>> map = needUploadObjectInfoMap.get(player.getUserId());
            if(map == null){
                map = new ConcurrentHashMap<>();
                needUploadObjectInfoMap.put(player.getUserId(),map);
            }
            Set set = map.get(type);
            if(set == null){
                set = new HashSet();
                map.put(type,set);
            }
            set.add(objectId);
        }
    }

    public static void uploadObjectInfo(){
        synchronized (needUploadObjectInfoMap) {
            for (Map.Entry<Long,ConcurrentHashMap<Integer,Set<Integer>>> entry : needUploadObjectInfoMap.entrySet()){
                long userId = entry.getKey();
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if(player == null){
                    continue;
                }
                MonopolyMarketProto.MonopolyMarketSynDispatchToCrossReqMsg.Builder synDispatch = MonopolyMarketProto.MonopolyMarketSynDispatchToCrossReqMsg.newBuilder();
                ConcurrentHashMap<Integer,Set<Integer>> map = entry.getValue();
                MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
                for (Map.Entry<Integer,Set<Integer>> item : map.entrySet()){
                    // 如果葫芦娃的技能 有更新 需要更新全部的派遣的门客
                    int type = item.getKey();
                    Set<Integer> set = item.getValue();
                    // 更新所有派遣的门客
                    boolean updateAllPatrons = PatronsMgr.hasSkillType(player,new ArrayList<>(set),eSkillType.CALABASH_BROTHERS_KING.getValue());
                    // 更新所有派遣的美女
                    boolean updateAllBeauty = PatronsMgr.hasSkillType(player,new ArrayList<>(set),eSkillType.CALABASH_BROTHERS_QUEEN.getValue());
                    if(updateAllPatrons){
                        Map<Integer, Set<MonopolyMarketResGrabDispatchInfo>> dispatchInfoListMap = marketModule.getCurDispatchInfoListMap(eMonopolyMarketResType.RES_KING.getValue(), false);
                        if(dispatchInfoListMap != null){
                            for (Set<MonopolyMarketResGrabDispatchInfo> dispatchInfos : dispatchInfoListMap.values()){
                                List<UserPatrons> patronsList = getDispatchPatronsList(player,dispatchInfos);
                                for (MonopolyMarketResGrabDispatchInfo dispatchInfo : dispatchInfos){
                                    // 同步有变化的门客
                                    UserPatrons patrons = player.getModule(PatronsModule.class).getUserPatrons(dispatchInfo.getDispatchId());
                                    synDispatch.addResGrabPatronsList(MonopolyMarketMgr.builderMonopolyMarketPatronsEntity(player,patrons,patronsList).build());
                                }
                            }
                        }
                    }else if(type == eMonopolyMarketResType.RES_KING.getValue()) {
                        // 获取需要同步的据点id
                        Set<Integer> pointSet = marketModule.getCurDispatchInfo(type,set);
                        for (int posIndex : pointSet){
                            // 同步有变化的门客
                            Map<Integer, Set<MonopolyMarketResGrabDispatchInfo>> curDispatchInfoListMap = marketModule.getCurDispatchInfoListMap(type,true);
                            Set<MonopolyMarketResGrabDispatchInfo> dispatchInfoSet =  curDispatchInfoListMap.get(posIndex);

                            List<UserPatrons> patronsList = getDispatchPatronsList(player,dispatchInfoSet);
                            for (MonopolyMarketResGrabDispatchInfo dispatchInfo : dispatchInfoSet){
                                // 同步有变化的门客
                                UserPatrons patrons = player.getModule(PatronsModule.class).getUserPatrons(dispatchInfo.getDispatchId());
                                synDispatch.addResGrabPatronsList(MonopolyMarketMgr.builderMonopolyMarketPatronsEntity(player,patrons,patronsList).build());
                            }
                        }
                    }
                    if(updateAllBeauty) {
                        Map<Integer, Set<MonopolyMarketResGrabDispatchInfo>> dispatchInfoListMap = marketModule.getCurDispatchInfoListMap(eMonopolyMarketResType.RES_QUEEN.getValue(), false);
                        if(dispatchInfoListMap != null){
                            int addPlus = PatronsMgr.getMonopolyMarketPatronsPlus(player, eSkillType.CALABASH_BROTHERS_QUEEN.getValue());
                            for (Set<MonopolyMarketResGrabDispatchInfo> dispatchInfos : dispatchInfoListMap.values()){
                                for (MonopolyMarketResGrabDispatchInfo dispatchInfo : dispatchInfos){
                                    // 同步有变化的门客
                                    UserBeauty beauty = player.getModule(BeautyModule.class).getUserBeauty(dispatchInfo.getDispatchId());
                                    synDispatch.addResGrabBeautyList(MonopolyMarketMgr.builderMonopolyMarketBeautyEntity(beauty,addPlus).build());
                                }
                            }
                        }
                    }else if(type == eMonopolyMarketResType.RES_QUEEN.getValue()) {
                        int addPlus = PatronsMgr.getMonopolyMarketPatronsPlus(player, eSkillType.CALABASH_BROTHERS_QUEEN.getValue());
                        for (int objectId : set){
                            if(marketModule.isDispatch(eMonopolyMarketResType.RES_QUEEN.getValue(),objectId)){
                                // 同步有变化的美女
                                UserBeauty beauty = player.getModule(BeautyModule.class).getUserBeauty(objectId);
                                synDispatch.addResGrabBeautyList(MonopolyMarketMgr.builderMonopolyMarketBeautyEntity(beauty,addPlus).build());
                            }
                        }
                    }
                    // 要塞
                    if(type == eMonopolyMarketResType.FORTRESS.getValue()){
                        for (Integer patronsId : item.getValue()){
                            if (!marketModule.getFortressDispatchMap().containsKey(patronsId)){
                                // 未派遣
                                continue;
                            }
                            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
                            if (userPatrons == null) {
                                continue;
                            }
                            synDispatch.addFortressPatronsList(MonopolyMarketMgr.builderMonopolyMarketFortressPatronsDispatchEntity(userPatrons));
                        }
                    }
                }
                if(synDispatch.getResGrabBeautyListCount() > 0 || synDispatch.getResGrabPatronsListCount() > 0 || synDispatch.getFortressPatronsListCount() > 0){
                    player.sendPacket(CrossProtocol.C_CROSS_MONOPOLY_MARKET_SYN_DISPATCH_INFO, synDispatch);
                }
            }
            needUploadObjectInfoMap.clear();
        }
    }

    /**
     * 刷新玩家待客茶数量
     * @param marketModule
     * @param now 需要计算的时间节点
     */
    public static void refreshOfficeTeaReward(MonopolyMarketModule marketModule,int now){
        if(marketModule.baseData.getOfficeCurPos() >= 0 && MonopolyMarketMgr.group != null && marketModule.baseData.getTeaLastGetTime() > 0){
            MonopolyMarketResConfigData configData = officeResConfigMap.get(marketModule.baseData.getOfficeLevel());
            int rate = MonopolyMarketCommonMgr.calResRate(MonopolyMarketMgr.group.getServerList().size(),configData.rewardValue2,configData.rewardAdd2,configData.getId(),MonopolyMarketMgr.backEndConfig,marketModule.baseData.getOfficeNo());
            int diff = now - marketModule.baseData.getTeaLastGetTime();
            int i = diff / GameConfig.MONOPOLYMARKET_REWARD_CD_1;
            if(i > 0 ){
                int rewardNum = i * rate;
                marketModule.baseData.setTeaLastNum(marketModule.baseData.getTeaLastNum() + rewardNum);
                marketModule.baseData.setTeaLastGetTime(marketModule.baseData.getTeaLastGetTime() + i * GameConfig.MONOPOLYMARKET_REWARD_CD_1);
            }
        }

    }

    /**
     * 刷新体力
     * @param marketModule
     * @param forceUpdate
     */
    public static void refreshPhysical(MonopolyMarketModule marketModule ,int endTime ,boolean forceUpdate){
        // 刷新体力
        long diffTime = endTime - marketModule.baseData.getPhysicalRefreshTime();
        int physicalMaxLimit = MonopolyMarketMgr.calPhysicalMaxLimit(marketModule);
        if (marketModule.baseData.getPhysical() < physicalMaxLimit) {
            int timesCD = (int)(diffTime / GameConfig.MONOPOLYMARKET_REWARD_CD_1);
            if (timesCD > 0 ) {
                int productionRate = MonopolyMarketMgr.calOfficeSeatProductionRate(marketModule);
                int times = timesCD * productionRate;
                if (times + marketModule.baseData.getPhysical() < physicalMaxLimit) {
                    marketModule.baseData.setPhysicalRefreshTime(marketModule.baseData.getPhysicalRefreshTime() + timesCD * GameConfig.MONOPOLYMARKET_REWARD_CD_1);
                    marketModule.baseData.setPhysical(marketModule.baseData.getPhysical() + times);
                }else {
                    marketModule.baseData.setPhysicalRefreshTime(endTime);
                    marketModule.baseData.setPhysical(physicalMaxLimit);
                }
            }
        } else {
            if (forceUpdate) {
                marketModule.baseData.setPhysicalRefreshTime(endTime);
            }
        }
    }


    /**
     * 玩家离开座位的时间 （因为周重置）
     * @param marketModule
     * @return 0 表示没有 入座
     */
    public static int exitOfficeTime(MonopolyMarketModule marketModule){
        if(marketModule.baseData.getOfficeCurPos() >= 0){
            // 有入座
            return MonopolyMarketCommonMgr.getResetOfficeTime((int)(marketModule.baseData.getPhysicalRefreshTime()), ConfigMgr.getOfficeEndSecond());
        }
        return 0;
    }

    /**
     * 发送待客茶道具
     */
    public static void sendOfficeRewardMail(MonopolyMarketModule marketModule){
        if(marketModule.baseData.getTeaLastNum() > 0){
            Property property = new Property(GameConfig.MONOPOLYMARKET_GUEST_TEA_ID, BigInteger.valueOf(marketModule.baseData.getTeaLastNum()));
            String language = UserMgr.getLanguage(marketModule.baseData.getUserId());
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_OFFICE_REWARD_TITLE, language);
            String mailContent = MultipleLanguageMgr.getContent(MailManager.MONOPOLY_MARKET_OFFICE_REWARD_CONTENT, language);
            mailContent = StringUtils.format(mailContent, marketModule.baseData.getTeaLastNum());
            MailManager.sendMail(marketModule.baseData.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(property),mailContent,mailTitle);
            marketModule.baseData.setTeaLastNum(0);
        }
        marketModule.baseData.setTeaLastGetTime(0);
    }

    /**
     * 获取set里面的id集合
     * @param set
     * @return
     */
    public static List<UserPatrons> getDispatchPatronsList(GamePlayer player,Set<MonopolyMarketResGrabDispatchInfo> set){
        List<UserPatrons> patronsList = new ArrayList<>();
        for (MonopolyMarketResGrabDispatchInfo dispatchInfo : set){
            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(dispatchInfo.getDispatchId());
            patronsList.add(userPatrons);
        }
        return patronsList;
    }


    public static MonopolyMarketUserData getMonopolyMarketUserData(long userId, boolean newIfNull){
        MonopolyMarketUserData baseData = MonopolyMarketBussiness.getMonopolyMarketUserData(userId);
        if(baseData == null && newIfNull){
            baseData = new MonopolyMarketUserData();
            baseData.setInsertOption();
            baseData.setUserId(userId);
            baseData.setPhysical(GameConfig.MONOPOLYMARKET_INITIAL_GUANYIN_MAX);
            baseData.setPhysicalRefreshTime(DateHelper.getCurrentSecond());
            baseData.setTeaLastGetTime(DateHelper.getCurrentSecond());
        }
        return baseData;
    }


    /**
     * 判断玩家要塞是否可以派遣玩家
     * @return
     */
    public static boolean canDispatchFortress(GamePlayer player){
        UnionMember unionMember = CrossUnionMgr.getUnionMember(player.getUserId());
        if(unionMember == null){
            return false;
        }
        return group.getFortressCanJoinUnionIdList().contains(unionMember.getUnionUid());
    }

    /**
     * 尝试锁定 要塞参与资格
     */
    public static synchronized void lockFortressJoinUnion() {
        if (group == null) {
            return;
        }
        int now = DateHelper.getCurrentSecond();
        int lockJoinUnionTime = DateHelper.getWeekBeginTimestamp(now) + ConfigMgr.getFortressDispatchPeriodOpenSecond();
        if (group.getFortressLockJoinUnionLastTime() < lockJoinUnionTime && now >= lockJoinUnionTime) {
            synchronized (group) {
                if (group.getFortressLockJoinUnionLastTime() < lockJoinUnionTime) {
                    group.getFortressCanJoinUnionIdList().clear();
                    // 本周派遣期开始 并未锁定过
                    List<UnionInfo> allUnionList = new ArrayList(CrossUnionMgr.getUnionInfoMap().values());
                    allUnionList.sort((t1, t2) -> {
                        return Long.compare(t2.getTotalEarnSpeed().longValue(), t1.getTotalEarnSpeed().longValue());
                    });
                    List<String> canJoinUnionIdList = new ArrayList<>();
                    int num = GameConfig.MONOPOLYMARKET_BIANGUAN_PAIQIAN;
                    for (UnionInfo item : allUnionList) {
                        if (num-- <= 0) {
                            break;
                        }
                        canJoinUnionIdList.add(item.getUnionUid());
                    }
                    group.setFortressCanJoinUnionIdList(canJoinUnionIdList);
                    group.setFortressLockJoinUnionLastTime(lockJoinUnionTime);
                }
            }
        }
    }

    /**
     * 是否锁定了本周参与联盟
     *
     * @return
     */
    public static boolean isLockJoinUnion(){
        int lockJoinUnionTime = DateHelper.getWeekBeginTimestamp() + ConfigMgr.getFortressDispatchPeriodOpenSecond();
        if (group.getFortressLockJoinUnionLastTime() < lockJoinUnionTime) {
            return false;
        }
        return true;
    }

    /**
     * 结算期 锁定参与的联盟成员给跨服
     */
    public static synchronized void lockFortressJoinUnionMember(){
        if (group == null) {
            return;
        }
        int now = DateHelper.getCurrentSecond();
        // 锁定联盟中参赛的玩家 锁定联盟数据
        int lockJoinMemberTime = DateHelper.getWeekBeginTimestamp(now) + ConfigMgr.getFortressDispatchPeriodEndSecond();
        if(group.getFortressLockJoinUnionMemberLastTime() < lockJoinMemberTime && now >= lockJoinMemberTime) {
            // 给跨服同步锁定数据
            MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.Builder crossMsg = MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.newBuilder();
            crossMsg.setType(2);
            for (String unionId : group.getFortressCanJoinUnionIdList()){
                UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionId);
                if(unionInfo == null){
                    continue;
                }
                UserInfo leaderInfo = UserMgr.getUserInfo(unionInfo.getMasterUserId());
                MonopolyMarketProto.MonopolyMarketFortressLockUnionInfoEntity.Builder lockUnionInfo = MonopolyMarketProto.MonopolyMarketFortressLockUnionInfoEntity.newBuilder();
                lockUnionInfo.setUnionId(unionId);
                UnionBaseInfo unionBaseInfo = UnionHelper.parseUnionBaseInfo(unionInfo, leaderInfo, GameServer.getInstance().getServerId());
                UnionProto.UnionBaseTempMsg.Builder unionMsg = UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo);
                // 联盟信息
                lockUnionInfo.setUnionInfo(unionMsg);
                Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionId);
                for (Long memberId : memberMap.keySet()){
                    lockUnionInfo.addMemberList(memberId);
                }
                crossMsg.addLockUnionList(lockUnionInfo);
            }
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_MONOPOLY_MARKET_FORTRESS_SYN_INFO, crossMsg));
        }
    }


    /**
     * 获取玩家 代表出战的
     * @param userId
     * @return 没有资格 返回""
     */
    public static String getJoinFortressUnionId(long userId){
        if(isLockJoinUnion()){
            // 因为锁定的时候定时器 有时间延迟，所以有能在节点后几秒之后锁定
            UnionMember unionMember = CrossUnionMgr.getUnionMember(userId);
            if (unionMember != null && group.getFortressCanJoinUnionIdList().contains(unionMember.getUnionUid())) {
                return unionMember.getUnionUid();
            }
        }
        return "";
    }

    /**
     * 离开联盟 移除 要塞派遣 所有的 派遣
     */
    public static void leaveUnion(String unionId, long userId){
        if(group == null){
            return;
        }
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            // 不是在派遣期
            return;
        }
        if(!group.getFortressCanJoinUnionIdList().contains(unionId)){
            // 没有参赛资格
            return;
        }
        // 通知跨服移除玩家派遣的大臣
        MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.newBuilder();
        builder.setType(1);
        builder.setUnionId(unionId);
        builder.setUserId(userId);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_MONOPOLY_MARKET_FORTRESS_SYN_INFO, builder));
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if(player != null){
            MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
            marketModule.getFortressDispatchMap().clear();
            player.getModule(MonopolyMarketModule.class).synRoleData();
        }
    }

    /**
     * 解散联盟
     */
    public static void deleteUnion(List<Long> syncUserIdList, String unionId){
        if(group == null){
            return;
        }
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            // 不是在派遣期
            return;
        }
        if(!group.getFortressCanJoinUnionIdList().contains(unionId)){
            // 没有参赛资格
            return;
        }
        group.getFortressCanJoinUnionIdList().remove(unionId);
        // 通知跨服删除该参赛联盟 并移除所以玩家的派遣
        MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.newBuilder();
        builder.setType(0);
        builder.setUnionId(unionId);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_MONOPOLY_MARKET_FORTRESS_SYN_INFO, builder));

        for (long userId : syncUserIdList){
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player != null){
                MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
                marketModule.getFortressDispatchMap().clear();
                player.getModule(MonopolyMarketModule.class).synRoleData();
            }
        }
    }

    /**
     * 改变联盟名称
     */
    public static void changeUnionName(String unionId,String unionName) {
        if(group == null){
            return;
        }
        if(!MonopolyMarketCommonMgr.isDispatchFortress()){
            // 不是在派遣期
            return;
        }
        if(!group.getFortressCanJoinUnionIdList().contains(unionId)){
            // 没有参赛资格
            return;
        }
        MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.Builder builder = MonopolyMarketProto.MonopolyMarketFortressSynInfoToCrossMsg.newBuilder();
        builder.setType(3);
        builder.setUnionId(unionId);
        builder.setUnionName(unionName);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_MONOPOLY_MARKET_FORTRESS_SYN_INFO, builder));
    }

    /**
     * 尝试领取 要塞采集奖励
     * @param player
     */
    public static void attemptReceiveCollectReward(GamePlayer player){
        UnionMember unionMember = CrossUnionMgr.getUnionMember(player.getUserId());
        if(unionMember == null){
            return;
        }
        if(!canEnterSystem(player)){
            return;
        }
        if(!group.getFortressCanJoinUnionIdList().contains(unionMember.getUnionUid())){
            return;
        }
        MonopolyMarketModule marketModule = player.getModule(MonopolyMarketModule.class);
        if(marketModule.inSystemId > -1){
            player.sendPacket(YanQuMessageUtils.buildMessage(CrossProtocol.C_MONOPOLY_MARKET_FORTRESS_RANK_RECEIVE_COLLECT_REWARD));
        }
    }


    public static void resetFortressUserInfo(){

    }

}
